package com.koi.mqttdemo;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import com.koi.mqttdemo.service.MqttConnectionService;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;

public class Mqtt {
    private static final String TAG = Mqtt.class.getSimpleName();

    private Context mContext;
    // 服务器地址（协议+地址+端口号）
    private String mHostUri = "";
    // 客户端标识
    private String mClientId = "";
    // 用户名称
    private String mUserName = "";
    // 密码.将字符串转换为字符串数组
    private String mUserPswd = "";
    //清除缓存
    private boolean mIsCleanSession = true;
    //设置超时时间，单位：秒
    private int mTimeoutConnection = 10;
    // 心跳包发送间隔，单位：秒
    private int mKeepAliveInterval = 10;

    private MqttAndroidClient mMqttAndroidClient;
    private MqttConnectOptions mMqttConnectOptions = new MqttConnectOptions();
    // MQTT监听并且接受消息
    private  MqttCallback mMqttCallback = new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            Log.d(TAG, "connectionLost");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            String msg = new String(message.getPayload());
            if (topic.equals(mSubscribeTopics[0])) {
                MqttConnectionService.getMqttReceiveCallBack().setguangminMsg(msg+" lx");
            } else if (topic.equals(mSubscribeTopics[1])) {
                MqttConnectionService.getMqttReceiveCallBack().setWenDuMsg(msg+" ℃");
            } else if (topic.equals(mSubscribeTopics[2])) {
                MqttConnectionService.getMqttReceiveCallBack().setShiDuMsg(msg+" %");
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    };

    // 回调函数，mqtt连接主机成功或失败时的处理函数
    private IMqttActionListener mMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            setSubscribeTopic(mSubscribeTopics, 0);
            Log.d(TAG, "连接成功");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            exception.printStackTrace();
            Log.d(TAG, "连接失败");
        }
    };

    // 订阅的主题
    private String[] mSubscribeTopics = {
            "null/null/Sensor/00:09:C0:FF:EC:48/00:12:4B:00:06:1B:65:2E/0/01",
            "null/null/Sensor/00:09:C0:FF:EC:48/00:12:4B:00:06:1B:65:46/0/01",
            "null/null/Sensor/00:09:C0:FF:EC:48/00:12:4B:00:06:1B:65:46/1/01" };
    private String mSendTopic = "null/null/Actuator/00:09:C0:FF:EC:48/00:12:4B:00:06:1B:65:5D/1/02";
    public void initMqttClient(Context context,
                               String hostUri,
                               String clientId,
                               String userName,
                               String userPswd,
                               boolean isCleanSession,
                               int timeoutConnection,
                               int keepAliveInterval) {
        mContext = context;
        mHostUri = hostUri;
        mClientId = clientId;
        mMqttAndroidClient = new MqttAndroidClient(mContext, mHostUri, mClientId);
        // 设置MQTT监听并且接受消息
        mMqttAndroidClient.setCallback(mMqttCallback);


        mUserName = userName;
        mUserPswd = userPswd;
        mIsCleanSession = isCleanSession;
        mTimeoutConnection = timeoutConnection;
        mKeepAliveInterval = keepAliveInterval;
        // Mqtt连接选项
        mMqttConnectOptions.setCleanSession(mIsCleanSession);
        mMqttConnectOptions.setConnectionTimeout(mTimeoutConnection);
        mMqttConnectOptions.setKeepAliveInterval(mKeepAliveInterval);
        if (!TextUtils.isEmpty(mUserName)) {
            mMqttConnectOptions.setUserName(mUserName);
        }
        if (!TextUtils.isEmpty(mUserPswd)) {
            mMqttConnectOptions.setPassword(mUserPswd.toCharArray());
        }
    }

    public int doConnect() {
        if (! mMqttAndroidClient.isConnected() && isCouldConnect()) {
            try {
                mMqttAndroidClient.connect(mMqttConnectOptions, null, mMqttActionListener);
                return 0;
            } catch (MqttException e) {
                e.printStackTrace();
                return -1;
            }
        }
        return 1;
    }

    /** 判断网络是否连接 */
    private boolean isCouldConnect() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            Log.i(TAG, "MQTT当前网络名称：" + name);
            return true;
        } else {
            Log.i(TAG, "MQTT 没有可用网络");
            return false;
        }
    }

    public MqttAndroidClient getMqttAndroidClientInstance() {
        if (mMqttAndroidClient != null) {
            mMqttAndroidClient = new MqttAndroidClient(mContext, mHostUri, mClientId);
            // 设置MQTT监听并且接受消息
            mMqttAndroidClient.setCallback(mMqttCallback);
        }
        return mMqttAndroidClient;
    }

    // 发送主题消息
    public boolean sendTopic(String sendTopic, String sendMessage) {
        if (mMqttAndroidClient.isConnected()) {
            mMqttConnectOptions.setWill(sendTopic, sendMessage.getBytes(), 0, false);
            try {
                mMqttAndroidClient.publish(sendTopic, sendMessage.getBytes(), 0, false);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    public boolean sendTopic(String sendTopic, String sendMessage, int qos,Boolean retained) {
        if (mMqttAndroidClient.isConnected()) {
            mMqttConnectOptions.setWill(sendTopic, sendMessage.getBytes(), qos, retained.booleanValue());
            try {
                mMqttAndroidClient.publish(sendTopic, sendMessage.getBytes(), qos, retained);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    // 设置订阅
    private boolean setSubscribeTopic(String[] subscribeTopics, int qos) {
        for (String subTopic : subscribeTopics) {
            try {
                mMqttAndroidClient.subscribe(subTopic, 0);
            } catch (MqttException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
}
